package cn.yuemouren.security.core.social.qq.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.io.IOException;

/**
 * @Author: Timi
 * @Description: QQ实现类
 * @Date: 2020/6/22 21:56
 * @Version: v1.0
 */
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private static final String GET_OPENID_URL = "https://graph.qq.com/oauth2.0/me?access_token=%s";

    private static final String GET_USERINFO_URL = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";
    //应用id
    private String appId;
    //用户身份的标识
    private String openId;

    private ObjectMapper mapper = new ObjectMapper();

    public QQImpl(String accessToken,String appId){
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
        String openUrl = String.format(GET_OPENID_URL, accessToken);
        String result = getRestTemplate().getForObject(openUrl, String.class);
        logger.info("result:"+result);
        this.appId = appId;
        //注意去掉双引号
        this.openId = StringUtils.substringBetween(result,"\"openid\":\"", "\"}");
    }

    @Override
    public QQUserInfo getUserInfo() {
        String userInfoUrl = String.format(GET_USERINFO_URL, appId, openId);
        String result = getRestTemplate().getForObject(userInfoUrl, String.class);
        logger.info("获取qq用户信息返回值："+result);
        try {
            QQUserInfo qqUserInfo = mapper.readValue(result, QQUserInfo.class);
            //将openId 放入到User信息中
            qqUserInfo.setOpenId(openId);
            return qqUserInfo;
        } catch (IOException e) {
            throw new RuntimeException("用户获取失败");
        }
    }
}
